package com.java.nio;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author jl
 * Created on 2020/9/27
 * Scattering:将数据写入buffer时,可以采用buffer数组,依次写入 [分散]
 * Gathering:从buffer读取数据时,可以采用buffer数组,依次读 [聚合]
 */
public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws Exception {
        // 使用serverSocketChannel和socketChannel网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        // 绑定端口到socket并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        // 创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端连接 telnet
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLength = 8;
        // 循环读取
        while (true) {
            int read = 0;
            while (read < messageLength) {
                long l = socketChannel.read(byteBuffers);
                read += l; // 累计读取的字节数
                System.out.println("read=" + read);
                Arrays.stream(byteBuffers).map(b -> "position=" + b.position() + ",limit=" + b.limit()).forEach(System.out::println);
            }

            Arrays.stream(byteBuffers).forEach(Buffer::flip);

            // 将数据从buffer中写入channel
            int write = 0;
            while (write < messageLength) {
                long l = socketChannel.write(byteBuffers);
                write += l;
                System.out.println("write=" + write);
            }

            // 清空byteBuffer,重置标志位
            Arrays.stream(byteBuffers).forEach(Buffer::clear);
            System.out.println("read=" + read + ",write=" + write);
        }

    }
}
